package com.luxuewen.sxa.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Map;

@Slf4j
@Component
@Configuration
public class JwtUtils {
    private static String secret;
    // 获取jwt密钥
    @Value("${jwt.secret}")
    public void setSecret (String secret) {
        JwtUtils.secret = secret;
    }

    private static String issuer;
    // 获取jwt发行人
    @Value("${jwt.issuer}")
    public void setIssuer (String issuer) {
        JwtUtils.issuer = issuer;
    }

    private static Integer expires;
    // 获取jwt过期时间
    @Value("${jwt.expires}")
    public void setExpires (Integer expires) {
        JwtUtils.expires = expires;
    }

    /**
     * 生成token
     * @param payload token载荷
     * @return token
     * @throws JWTCreationException -
     */
    public static String generateToken (Map<String, Object> payload) throws JWTCreationException {
        Algorithm algorithm = Algorithm.HMAC256(secret);

        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND, expires);

        return JWT.create()
                .withClaim("user_infos", payload)
                .withIssuer(issuer)
                .withExpiresAt(instance.getTime())
                .sign(algorithm);
    }

    /**
     * 验证token
     * @param token 待验证token
     * @return 包含的信息
     * @throws JWTVerificationException 异常
     */
    public static Map<String, Object> verifyToken (String token) throws JWTVerificationException {
        Algorithm algorithm = Algorithm.HMAC256(secret);

        return JWT.require(algorithm)
                .withIssuer(issuer)
                .build()
                .verify(token)
                .getClaim("user_infos")
                .asMap();
    }
}
